#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/resource.h>

#define BUFSIZE     4096
#define FILE_MODE   S_IRUSR|S_IWUSR|S_IRGRP|S_IRGRP|S_IROTH|S_IWOTH

int main(int argc, char const* argv[])
{
    int fdin, fdout, n;
    char buf[BUFSIZE];
    struct rusage ru;

    if (argc != 3)
    {
        fprintf(stderr, "usage: %s <fromfile><tofile>\n", argv[0]);
        exit(0);
    }
    
    if ((fdin = open(argv[1], O_RDONLY)) < 0)
    {
        fprintf(stderr, "open %s error\n", argv[1]); 
        exit(0); 
    }

    if ((fdout = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, FILE_MODE)) < 0)
    {
        fprintf(stderr, "open %s error\n", argv[2]); 
        exit(0); 
    }

    while ((n = read(fdin, buf, BUFSIZE)) > 0)
        if (write(fdout, buf, n) != n)
        {
            perror("write error");
            exit(0);
        }

    if (n < 0)
    {
        perror("read error");
        exit(0);
    }

    if (getrusage(RUSAGE_SELF, &ru) < 0)
    {
        perror("getrusage error");
        exit(0);
    }

    printf("user time: %ld.%06ld\n", ru.ru_utime.tv_sec,
        ru.ru_utime.tv_usec);
    printf("sys time: %ld.%06ld\n", ru.ru_stime.tv_sec,
        ru.ru_stime.tv_usec);

    return 0;
}
